package com.zs.propertymanage.inteceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zs.propertymanage.utils.JwtUtil;
import com.zs.propertymanage.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 此拦截器拦截除"/login"以外的所有请求
 * 此拦截器作用是利用JWT进行访问身份权限认证
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //令牌验证
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer "))
            token = token.replace("Bearer ", "");
        else {
            // token格式不正确
            handleResponse(response, "访问身份未经授权，请登录！");
            return false;
        }
        //验证token是否有效
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            String id = (String) claims.get("id");
            // 能解析成功说明token是有效的，接下来再与redis中的token进行比较
            String redisToken = stringRedisTemplate.opsForValue().get("user jwt token:" + id);
            if (!token.equals(redisToken)) {
                handleResponse(response, "身份令牌已更改，请重新登录");
                return false;
            }
            // 执行到这里，说明token有效，将token放入线程本地存储
            ThreadLocalUtil.set(token);     // 目前是提供给日志AOP（LogAspect）用于操作方信息解析
            return true;
        } catch (com.auth0.jwt.exceptions.TokenExpiredException e) {
            handleResponse(response, "身份令牌已过期，请重新登录");  // 于"+e.getExpiredOn()+"
            return false;
        } catch (Exception e) {
            handleResponse(response, "身份令牌无效，请重新登录");
            return false;
        }
    }

    // 返回[访问未授权或身份过期]消息进行提醒
    private void handleResponse(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(401);    // http响应状态码为401
        Map<String, Object> map = new HashMap<>();
        map.put("msg", msg);
        map.put("code", 401);
        map.put("data", null);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }

}